function fne(ev){
ev.style.display="block"
}
function fnl(ev){
ev.style.display="none"
}
function tocart(){
    location="mycarts.html"
}
function fnleave(ev){
    ev.style.textDecoration="none"
    ev.style.border="none"
}
function fnlog(ev){
  ev.style.display="block"
  regin.style.display="none"
  }
 function fnregn(ev){
    ev.style.display="block"
    login.style.display="none"
    }

//选项卡效果
if(document.querySelector("title").innerHTML=="首页"){
  document.querySelectorAll(".p-list-box")[0].style.textDecoration="underline"
  let menubox=document.querySelector(".menu-box")
  document.querySelectorAll(".p-list-box").forEach((v,i)=>{
    v.onmouseenter=()=>{
    v.style.textDecoration="underline"
    v.style.border="1px solid black"
    switch(i){
      case 0 :
        document.querySelector(".menu-box").style.left="80px";
        break;
      case 1 :
        document.querySelector(".menu-box").style.left="330px";
        break;
      case 2 :
        document.querySelector(".menu-box").style.left="590px";
        break;
      case 3 :
        document.querySelector(".menu-box").style.left="840px";
         break; 
    }
    }
  })

}

//广告轮播
var mySwiper = new Swiper(".swiper-container1", {
    loop: true, // 循环模式选项

    //自动播放
    autoplay: {
      delay: 2500,
      pauseOnMouseEnter: true,
      disableOnInteraction: false,
    },
    //过度效果
    effect: "slide",
  });

//轮播图效果
var mySwiper2 = new Swiper(".swiper-container2", {
  loop: true, // 循环模式选项
  // 前进后退按钮
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev",
  },
     // 分页器
pagination: {
  el: ".swiper-pagination",
  clickable: true,
  renderBullet:function(index,className){
    switch(index){
    case 0:text='CONVERSE一键购';break;
    case 1:text='星座系列';break;
    case 2:text='把未来造响';break;
    case 3:text='腰果花系列';break;
    case 4:text='CHUCK 70夏日新色';break;
    case 5:text='CX未来系列';break;
  }
  return '<span class="' + className + '">' + text + '</span>';
  }
},
  //自动播放
  autoplay: {
    delay: 3000,
    pauseOnMouseEnter: true,
    disableOnInteraction: false,
  },
  //过度效果
  effect: "slide",
});

//判断是否存在本地id
if(localStorage.getItem("username")){
    document.querySelector(".login-regin").innerHTML=`用户${localStorage.getItem("username")}:您好 <span onclick="fnquit()">退出</span> `
}
//加载页面商品信息函数
async function loadList() {
    let pagenum = 0;
    let pagesize = 8;
    let uid = 66751;
    let res=await axios.get(ProductListAPI, { params:{pagenum, pagesize, uid} })
    let html=res.data.data.map((v)=>`
    <div class="list-product-box">
    <a href="update.html?pid=${v.pid}"><img src="${v.pimg}"></a>
    <p class="pl-name">${v.pname}</p>
    <p class="pl-price">￥599</p>
    <p class="pl-price-now">￥${v.pprice}</p>
    </div>`).join("")
    document.querySelectorAll(".list-product").forEach(v=>v.innerHTML=html)
}
//判断在首页才加载商品信息函数
if(document.querySelector("title").innerHTML=="首页"){
console.log(document.querySelector("title").innerHTML);
    loadList()
}

//登录页接口
//判断登录id输入是否有误
function fnloginid(){
    /^\w{6,16}$/.test(document.querySelector(".ipt-id").value)
    ?document.querySelector(".ipt-id").nextElementSibling.innerHTML="账号格式正确"
    :document.querySelector(".ipt-id").nextElementSibling.innerHTML="账号格式错误"
}
//判断登录密码是否输入有误
function fnloginpw(){
    /^.{6,16}$/.test(document.querySelector(".ipt-pw").value)
    ?document.querySelector(".ipt-pw").nextElementSibling.innerHTML="密码格式正确"
    :document.querySelector(".ipt-pw").nextElementSibling.innerHTML="密码格式错误"
}
//登录按钮添加接口
document.querySelector("#login-btn").onclick=async function(){
    let username=document.querySelector(".ipt-id").value
    let password=document.querySelector(".ipt-pw").value
    let res=await axios.get(LoginAPI,{params:{username,password}})
    if(res.data.code==1){
        alert(res.data.msg)
        //登录
        let { id, token } = res.data.data;
        localStorage.setItem("username", username);
        localStorage.setItem("uid", id);
        localStorage.setItem("token", token);
        login.style.display="none"
        document.querySelector(".login-regin").innerHTML=`用户${localStorage.getItem("username")}:您好 <span onclick="fnquit()">退出</span> `
        location.reload() 
    }
}
//注册按钮事件
function fnel(){
    login.style.display="none"
    regin.style.display="block"
}
//退出按钮函数
function fnquit(){
    localStorage.removeItem("username");
    localStorage.removeItem("uid");
    localStorage.removeItem("token");
    document.querySelector(".login-regin").innerHTML=`<span onclick="fne(login)">登录</span>/<span>注册</span>`
    location.reload();
}

//注册接口
//先判断输入框内容
function fnphone(){
   /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(document.querySelector(".reg-phone").value)
    ?document.querySelector(".reg-phone").nextElementSibling.innerHTML="手机账号格式正确"
    :document.querySelector(".reg-phone").nextElementSibling.innerHTML="手机账号格式错误"
}
function fnmail(){
/[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}/.test(document.querySelector(".reg-mail").value)
?document.querySelector(".reg-mail").nextElementSibling.innerHTML="邮箱格式正确"
:document.querySelector(".reg-mail").nextElementSibling.innerHTML="邮箱格式错误"
}
function fnregid(){
    /^\w{6,16}$/.test(document.querySelector(".reg-id").value)
    ?document.querySelector(".reg-id").nextElementSibling.innerHTML="账号格式正确"
    :document.querySelector(".reg-id").nextElementSibling.innerHTML="账号格式错误"
}
//判断账号是否被注册过
async function fnjudgeid(){
   let username=document.querySelector(".reg-id").value
   let res= await axios.get(CheckNameAPI,{params:{username}})
   console.log(res);
res.data.code==1
?document.querySelector(".reg-id").nextElementSibling.innerHTML="恭喜你账号可用"
:document.querySelector(".reg-id").nextElementSibling.innerHTML="抱歉账号已被注册"
}

function fnregpw(){
    /^.{6,16}$/.test(document.querySelector(".reg-pw").value)
    ?document.querySelector(".reg-pw").nextElementSibling.innerHTML="密码格式正确"
    :document.querySelector(".reg-pw").nextElementSibling.innerHTML="密码格式错误"
}
function fnpwjudge(){
    document.querySelector(".reg-pw").value==document.querySelector(".reg-pw-judge").value
    ?document.querySelector(".reg-pw-judge").nextElementSibling.innerHTML="密码确认无误"
    :document.querySelector(".reg-pw-judge").nextElementSibling.innerHTML="两次密码不一致"
}
//注册按钮添加事件
async function fnreg(){
    if(document.querySelector(".reg-phone").nextElementSibling.innerHTML=="手机账号格式正确"
    &&document.querySelector(".reg-id").nextElementSibling.innerHTML=="恭喜你账号可用"
    &&document.querySelector(".reg-mail").nextElementSibling.innerHTML=="邮箱格式正确"
    &&document.querySelector(".reg-pw-judge").nextElementSibling.innerHTML=="密码确认无误"
    ){  
        let username=document.querySelector(".reg-id").value
        let password=document.querySelector(".reg-pw").value
        let {data,status}=await axios.get(RegAPI,{params:{username,password}})
        if (data.code ===1) {             
            let {data,status}= await axios.get(LoginAPI,{params:{username, password}})
            if(status===200){
              localStorage.setItem("username",data.data.username)
              localStorage.setItem("uid",data.data.id)
              localStorage.setItem("token",data.data.token)
              regin.style.display="none"
              document.querySelector(".login-regin").innerHTML=`用户${localStorage.getItem("username")}:您好 <span onclick="fnquit()">退出</span> `
          }else{
              alert(`登录失败，错误码${status}`)
          }
          } else {
            alert(`注册失败，错误码${status}`);
          }
    }
}

//详情页

if(document.querySelector("title").innerHTML=="详情页"){
//判断有没有uid背传过来
if (new URLSearchParams(location.search).has("pid")) {
    //如果有拿到传过来的pid
    let id = new URLSearchParams(location.search).get("pid");

    async function produtDetail(){
        let res=await  axios.get(produtDetailAPI, {params:{id}})
        document.querySelector(".main-box").innerHTML=`<img src="${res.data.data.pimg}">`
        document.querySelector(".lit-img-left").innerHTML=`<img src="${res.data.data.pimg}">`
        document.querySelector(".lit-img-right").innerHTML=`<img src="${res.data.data.pimg}">`
        document.querySelector(".lit-dec").innerHTML=`${res.data.data.pdesc}`
        document.querySelector(".main-title").innerHTML=`${res.data.data.pname}￥${res.data.data.pprice}` 
        document.querySelectorAll(".img-list-main").forEach(v=>v.innerHTML=`<img src="${res.data.data.pimg}">` )
        //加入购物车函数
        document.querySelector(".add-cars").onclick=(async function(){
            let pid = res.data.data.pid;
            let pnum = document.querySelector(".num-right").value
            let uid = localStorage.getItem("uid")
            if(localStorage.getItem("uid")){
              let data= await axios.get(CartAddAPI,{params:{pnum, uid, pid}})
 
              if (data.status==200 ) console.log(data); alert("商品添加成功");
            }
            else{
              alert("请先登录")
            }
            
        })
    }
    produtDetail()
}else alert("请传入pid");
}
//购物车页
if(document.querySelector("title").innerHTML=="购物车"){
  if(localStorage.getItem("uid")){
    loadCartList()
  }else{
    alert("请先登录")
  }
 
    async function loadCartList() {
        //与服务器连接
        let id = localStorage.getItem("uid");
        console.log(id);
        let res=await axios.get(CartListAPI,{params:{id} })
        console.log(res);
        document.querySelector('.your-cart-number').innerHTML=res.data.data.length
        let html=res.data.data.map((v)=>`
        <div class="mycart-list">
        <div class="mycart-list-til">
          <input type="checkbox"  class="sel-ipt" onchange="singleSelClick()"/>
          <button onclick="delClick(${v.pid},this)">删除</button>
          <button>编辑</button>
        </div>
        <div class="mycart-list-img">
          <img src="${v.pimg}" alt="" />
          <div class="mli-til">
            <h1>${v.pname}</h1>
            <h1 class="calc-price">${v.pprice}</h1>
          </div>
        </div>
        <div class="mli-num">
          数量:
          <input type="button" value="+" onclick="addBtnClick(this,${v.pid})"/>
          <input type="text" value="${v.pnum}" class="pnum-ipt" />
          <input type="button" value="-" onclick="subBtnClick(this,${v.pid})"/>
        </div>
      </div>`).join("")
        document.querySelector("#mycart-list-box").innerHTML=html
      }
      
}

//创建删除函数
  async function delClick(pid,obj){
    let uid = localStorage.getItem("uid");
     let res =await axios.get(CartDelAPI,{params:{uid,pid}})
    obj.parentNode.parentNode.remove();
    countAllPrice()
    thecartnum()
    judgeproduct()
    }
//创建+-函数

async function addBtnClick(obj,pid){
let uid = localStorage.getItem("uid");
  //让输入框里的数值加1
  obj.nextElementSibling.value++
  //让服务器端购物车里的pnum加1
  let pnum=document.querySelector(".pnum-ipt").value
  let res=await axios.get(CartUpdateAPI,{params:{uid, pid, pnum}})
  countAllPrice()
}

async function subBtnClick(obj,pid){
let uid = localStorage.getItem("uid");
//先判断value的值，不能小于1
obj.previousElementSibling.value <= 1
?obj.previousElementSibling.value=1
:obj.previousElementSibling.value--;
let pnum=document.querySelector(".pnum-ipt").value
let res=await axios.get(CartUpdateAPI,{params:{uid, pid, pnum}})
countAllPrice()
}
//全选框
function allSelClick(ipt){
    document.querySelectorAll(".sel-ipt").forEach((v)=>v.checked=ipt.checked)
    document.querySelectorAll(".allChecked").forEach(v=>v.checked=ipt.checked)
    countAllPrice()
    judgeproduct()
 }
//单选框
function singleSelClick(){
    let arr=[]
    document.querySelectorAll(".sel-ipt").forEach((v)=>arr.push(v.checked))
    if(arr.every(v=>v==true)){
      document.querySelectorAll(".allChecked").forEach(v=>v.checked=true)
    }else document.querySelectorAll(".allChecked").forEach(v=>v.checked=false)
    countAllPrice()
    judgeproduct()
}
//计算价格
function countAllPrice(){
    let sum=0
    document.querySelectorAll(".sel-ipt").forEach((v)=>{
        if(v.checked==true){
            let pnum=Number(v.parentNode.parentNode.querySelector(".pnum-ipt").value)
            let price=Number(v.parentNode.parentNode.querySelector(".calc-price").innerHTML)
            sum+=pnum*price     
        }
    })
    document.querySelector(".scr-price-box").innerHTML=sum
}
//判断选了几件商品
function judgeproduct(){
  let num=0
  document.querySelectorAll(".sel-ipt").forEach((v)=>{
    if(v.checked){
      num++
    }
  })
  document.querySelectorAll('.product-checked').forEach(v=>v.innerHTML=num)
}
//判断购物车一共几件商品
async function thecartnum(){
  let id = localStorage.getItem("uid");
  let res=await axios.get(CartListAPI,{params:{id} })
  document.querySelector('.your-cart-number').innerHTML=res.data.data.length
}
